package com.ctsi.service;

import com.ctsi.utils.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description:
 * @projectName:demoActivit
 * @see:com.ctsi.service
 * @author:黎彬
 * @createTime:2021/4/9 10:14
 * @version:1.0
 */
@Service("permissionService")
public class PermissionService {

    public boolean hasPermi(String permission) {
        if (StringUtils.isEmpty(permission)) {
            return false;
        }
        //获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (StringUtils.isNull(authentication) || CollectionUtils.isEmpty(authentication.getAuthorities())) {
            return false;
        }

        List<String> collect = authentication.getAuthorities().stream().map(i -> {
            return i.getAuthority();
        }).collect(Collectors.toList());

        return hasPermissions(collect, permission);
    }


    /**
     * 判断是否包含权限
     *
     * @param permissions 权限列表
     * @param permission  权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(List<String> permissions, String permission) {
        return permissions.contains(StringUtils.trim(permission));
    }
}
